package com.dhms.vostok1.ui

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.ViewTreeObserver
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
import androidx.lifecycle.lifecycleScope
import com.dhms.lib.app.LibApplication
import com.dhms.vostok1.BuildConfig
import com.dhms.vostok1.MainApplication
import com.dhms.vostok1.databinding.ActivityStartingBinding
import com.dhms.vostok1.model.StartingViewModel
import com.dhms.vostok1.model.StartingViewModelFactory
import com.dhms.vostok1.model.WebSocketViewModel
import com.dhms.vostok1.repository.CheckInstrumentRepository
import com.dhms.vostok1.repository.FaultRepository
import com.dhms.vostok1.service.net.MockNetworkAPI
import com.dhms.vostok1.service.net.NetworkApi
import com.dhms.vostok1.ui.login.LoginActivity
import com.dhms.vostok1.ui.main.MainActivity
import com.dhms.vostok1.utils.NetworkState
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch

class StartingActivity : AppCompatActivity() {

    private val startingViewModel: StartingViewModel by viewModels {
        StartingViewModelFactory(
            FaultRepository.getInstance((application as MainApplication).database.faultDao()),
            CheckInstrumentRepository.getInstance((application as MainApplication).database.checkInstrumentDao())
        )
    }

    private lateinit var _binding: ActivityStartingBinding
    val binding get() = _binding
    private var requestDataInfo = false

    override fun onCreate(savedInstanceState: Bundle?) {
        installSplashScreen()

        super.onCreate(savedInstanceState)

        _binding = ActivityStartingBinding.inflate(layoutInflater)
        setContentView(binding.root)

        startingViewModel.setUserSharedPreferences(
//            getSharedPreferences(
//                getString(R.string.setting_preference_file_key),
//                Context.MODE_PRIVATE
//            )
            LibApplication.mmkv
        )
        startingViewModel.setSharedPreferences(
//            getSharedPreferences(
//                getString(R.string.setting_preference_file_key),
//                Context.MODE_PRIVATE
//            )
            LibApplication.mmkv
        )
        startingViewModel.getSettings()

        startingViewModel.settingMap.value?.let {
            Log.i(TAG, "初始化网络设置")
            if(it["BASE_URL"]==""||it["BASE_URL"]==null){
                startingViewModel.writeSettings(
                    mapOf(
                        "BASE_URL" to BuildConfig.APPCIRCLE_API_HOST
                    )
                )
            }
            NetworkApi.initNetwork(it["BASE_URL"] as String)
            //MockNetworkAPI.initNetwork("http://192.168.1.109:4523")
            MockNetworkAPI.initNetwork("http://192.168.16.30:4523")
            //NetworkApi.initNetwork("http://192.168.1.15:8003")
        }

        startingViewModel.getSavedUserInfo()

        lifecycleScope.launch {
            startingViewModel.faultLevelList.collectLatest {
                (application as MainApplication).faultLevel = it
            }
        }

        startingViewModel.isSavedUserInfoGotten.observe(this) {
            if (it == true) {
                WebSocketViewModel.instance.createWebSocket()
            }
        }

        WebSocketViewModel.instance.networkChange.observe(this) {
            if (it == NetworkState.NETWORK && !requestDataInfo) {
                startingViewModel.prepareData()
                requestDataInfo = true
            }
        }

        binding.root.viewTreeObserver.addOnPreDrawListener(
            object : ViewTreeObserver.OnPreDrawListener {
                override fun onPreDraw(): Boolean {
                    // 若还未拿到用户信息，则return false
                    if (startingViewModel.isSavedUserInfoGotten.value == null) {
                        return false
                    }
                    // 若用户信息不为空且数据未准备完，并返回false
                    if ((startingViewModel.isSavedUserInfoGotten.value == true && !startingViewModel.isDataPreparedDone() && WebSocketViewModel.instance.networkChange.value == NetworkState.NETWORK)
                    ) {
                        return false
                    }

                    binding.root.viewTreeObserver.removeOnPreDrawListener(this)
                    val intent = Intent(
                        this@StartingActivity,
                        if (startingViewModel.isSavedUserInfoGotten.value == true) MainActivity::class.java else LoginActivity::class.java
                    ).setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)

                    return true
                }
            }
        )
    }

    companion object {
        private const val TAG = "StartingActivity"
    }
}